//
//  Style0ViewController.m
//  PiPiPineapple
//
//  Created by 李晓东 on 17/11/7.
//  Copyright © 2017年 PeanutXu. All rights reserved.
//

#import "Style0ViewController.h"
#import "DoubleChromosphere_Extension.h"
#import "Style0TableViewDataSource.h"
#import "SQLiteManager.h"
#import "ThroadToServer.h"
#import "Tools.h"

#import "UIBarButtonItem+Category.h"

#import <Masonry.h>

typedef NS_ENUM(NSInteger, RefreshState) {
    RefreshStateNormal,//正常
    RefreshStatePulling1,//释放即可刷新
    RefreshStatePulling2,
    RefreshStateLoading//加载中
};

@interface Style0ViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) Style0TableViewDataSource *dataSource;


@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;

@property (nonatomic, strong) UILabel *refreshLabel;
@property (nonatomic, assign) RefreshState refreshState;

@property (nonatomic, strong) UIImageView *imageView;

@property (nonatomic, assign) BOOL needAnimation;


@property (nonatomic, strong) dispatch_source_t timer;
@end

//#define CRow 20

@implementation Style0ViewController

- (void)loadView{
    [super loadView];
    self.tableView = [[UITableView alloc]init];
    [self.view addSubview:self.tableView];
    
    
    
    _refreshLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, -20, 1, 44)];
    [self.view addSubview:_refreshLabel];
//    [_tableView setTableHeaderView:_refreshLabel];
    
    
    _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 1, 44)];
    [_refreshLabel addSubview:_imageView];
    
    self.array = [NSMutableArray array];
    self.dataSource = [[Style0TableViewDataSource alloc]initWithData:self.array];
    
    [self loadFromDataBase:nil andCount:CRow andParameter:nil andOperate:nil andOrder:@"expect"];
    
    _needAnimation = NO;
    
    [self setEdgesForExtendedLayout:UIRectEdgeNone];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.dataSource = _dataSource;
    self.tableView.delegate = self;
    
    UINib *nib = [UINib nibWithNibName:@"Style0TableViewCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"li"];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top).mas_offset(self.navigationController.navigationBar.frame.size.height * -1);
        make.left.mas_equalTo(self.view.mas_left);
        make.width.mas_equalTo(self.view.mas_width);
        make.bottom.mas_equalTo(self.view.mas_bottom);
    }];
    
    [_refreshLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.tableView.bounds.origin.y);
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
        make.height.mas_equalTo(64);
    }];

    [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(_refreshLabel.mas_top);
        make.center.mas_equalTo(_refreshLabel.center);
        make.width.mas_equalTo(_refreshLabel.mas_height);
        make.height.mas_equalTo(_refreshLabel.mas_height);
    }];
    
    // 上拉 UI
    _indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    self.tableView.tableFooterView = _indicatorView;

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"说明" style: UIBarButtonItemStylePlain target:self action:@selector(explain:) index:0];
    
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSLog(@"ccc");

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.tableView.contentOffset.y + scrollView.frame.size.height > scrollView.contentSize.height + 40 && ![_indicatorView isAnimating] ) {
        [_indicatorView startAnimating];
        self.refreshState = RefreshStateNormal;
        DoubleChromosphere *obj = (DoubleChromosphere *)_array.lastObject;
        [self loadFromDataBase:obj.returnIssueno andCount:CRow andParameter:@"expect" andOperate:@" < " andOrder:@"expect"];
    } else if (scrollView.contentOffset.y < 0 && scrollView.contentInset.top != 0 && fabs(scrollView.contentOffset.y) > scrollView.contentInset.top + 5 && fabs(scrollView.contentOffset.y) < scrollView.contentInset.top + 60 && _needAnimation == NO){
        // 再改变动画,任然还没开始刷新操作
        
        NSInteger percent = (fabs(scrollView.contentOffset.y) - scrollView.contentInset.top - 5) / 54 * 60;
        
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"dropdown_anim__%05ld.png", percent]];
        [_imageView setImage:image];
        self.refreshState = RefreshStatePulling2;
        NSLog(@"%f--%@", self.tableView.contentOffset.y * -1, [NSMutableString stringWithFormat:percent < 10 ? @"dropdown_anim__%04ld.png" : @"dropdown_anim__%05ld.png", percent]);
    } else if (scrollView.contentOffset.y < 0 && scrollView.contentInset.top != 0 && fabs(scrollView.contentOffset.y) > scrollView.contentInset.top + 60 && self.refreshState != RefreshStateLoading && !scrollView.isDragging){
        // 再改变动画,并开始刷新操作
        _needAnimation = YES;
        self.refreshState = RefreshStateLoading;
        NSLog(@"我去--%f", scrollView.contentInset.top);
//        [_tableView mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo(self.view.mas_top);
//        }];
        
        
    }
    
    
    
}

- (void)setRefreshState:(RefreshState)refreshState{
    DoubleChromosphere *dbLastestObj = (DoubleChromosphere *)_array.firstObject;
    _refreshState = refreshState;
    //    UIImageView *imageView = [[UIImageView alloc]init];
    switch (_refreshState) {
        case RefreshStateNormal:
            //            [_refreshLabel setBackgroundColor:[UIColor whiteColor]];
            
            break;
        case RefreshStatePulling1:
            //            [ _refreshLabel setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"normal"]]];
            break;
        case RefreshStatePulling2:
            
            
            //            [_refreshLabel setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"pull1"]]];
            break;
        case RefreshStateLoading:
            //            [_refreshLabel setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"pull2"]]];
            [_imageView setAnimationImages:@[[UIImage imageNamed:@"eat-1"], [UIImage imageNamed:@"eat-2"], [UIImage imageNamed:@"eat-3"]]];
            [_imageView setAnimationDuration:0.6];
            
            [_imageView startAnimating];
            
            [self loadFromDataBase:nil andCount:1 andParameter:@"expect" andOperate:@">" andOrder:@"expect"];
            break;
        default:
            break;
    }
}

- (void)loadFromNet:(NSString *)issueno andCount:(NSInteger)count{
    
    [[[ThroadToServer shareThroadToServer]initWithParams:^(NSArray *array){
        
        NSTimer *timer = [NSTimer timerWithTimeInterval:3.2 repeats:NO block:^(NSTimer * _Nonnull timer) {
//            [_tableView mas_updateConstraints:^(MASConstraintMaker *make) {
//                
//                make.top.mas_equalTo(self.view.mas_top).mas_offset(self.navigationController.navigationBar.frame.size.height * -1);
//            }];
            NSLog(@"当前线程-%@", [NSThread currentThread]);
            _imageView.image = nil;
            [_imageView stopAnimating];
            [_tableView.tableHeaderView setHidden:YES];
//            [self insertData:array needInsertDataBase:YES haveIndexSet:1];
        }];
        [[NSRunLoop mainRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
//        [self insertData:array needInsertDataBase:YES haveIndexSet:1];
        
    }] loadDoubleChromospheresByIssueno:issueno andRows:count];
}

/**
  从数据库中加载数据

 @param issueno 期号
 @param count 记录条数
 @param param 查询的条件
 @param operate 操作符
 @param order 排序类型
 */
- (void)loadFromDataBase:(NSString *)issueno andCount:(NSInteger)count andParameter:(NSString *)param andOperate:(NSString *)operate andOrder:(NSString *)order {
    
    // 第一次进入到这个 UI, 会先从数据库加载数据.当发现没有数据时,会向网络请求(获取多条记录).返回的结果集会被记录到数据库,以及加载 array, 并刷新 tableViewcell; 但当数据库有数据时,也会向网络请求(获取一条最新记录),然后和数据库最新的记录比较,记录下相差的期数diff.如果diff=0,则数据库有最新的,放弃这条记录,把记过加载到 array, 并刷新 tableView;否则则保存这条记录,再判断是否大于1.大于1的话,就在访问网络(获取多条记录),把再访问网络返回的记录加载刚才的查询结果中,再把值加载给 array 和记录到数据库,再刷新 tableView;
    
    // 再完成第一次加载后.上拉刷新时,需要取出当前 tableView中最后一条记录.以该记录为条件,先从数据库加载数据.如果数据库中没有记录,则以刚才去到的记录的期数为条件,向网络请求(获取多条记录),返回的结果记录到数据库,以及加载 array, 并刷新 tableView.如果数据库中有记录,则把返回的记录加载到 array 中,并判断返回的记录数是否达到 CRow 条.如果没有达到,则向网络请求(获取多条记录),返回结果集会记录到数据库,以及加载 array, 并刷新 tableVIewCell .如果已经达到,则只刷新 tableViewcell
    
    
    RetuenBlock returnBlock = ^(NSArray *array1, BOOL needRefresh){
        // 1.1如果存在,就从中加载,并判断是否是最新的期数
        if (array1.count == 0) {
            [array1 arrayByAddingObjectsFromArray:[[[ThroadToServer shareThroadToServer]initWithParams:^(NSArray *array){
                DoubleChromosphere *obj = (DoubleChromosphere *)array.lastObject;
                NSInteger diffCount = [obj.returnIssueno integerValue] - [((DoubleChromosphere *)_array.firstObject).returnIssueno integerValue];
                if (diffCount > 1) {
                    [self loadFromNet:obj.returnIssueno andCount:diffCount - 1];
                }
            
//                [self insertData:array needInsertDataBase:YES haveIndexSet:0];
                
                
                
                
            }] loadDoubleChromospheresByIssueno:issueno andRows:count]];
        } else if (array1.count < CRow) {
            [self.array addObjectsFromArray:array1];
            
            DoubleChromosphere *dbLastestObj = (DoubleChromosphere *)array1.firstObject;
            // array返回的是网络最新的一条记录
            [[[ThroadToServer shareThroadToServer]initWithParams:^(NSArray *array2){
                DoubleChromosphere *lastestObj = (DoubleChromosphere *)array2.lastObject;
                NSInteger diff = [lastestObj.returnIssueno integerValue] - [dbLastestObj.returnIssueno integerValue];
                if (diff > 0) {
                    [self.array insertObject:lastestObj atIndex:0];
                    
                    NSMutableDictionary *lastestDict = [NSMutableDictionary dictionary];
                    [lastestDict addEntriesFromDictionary:[lastestObj dictionaryWithValuesForKeys:@[@"redA", @"redB", @"redC", @"redD", @"redE", @"redF", @"blue"]]];
                    
                    lastestDict[@"opentime"] = lastestObj.returnOpendate;
                    lastestDict[@"expect"] = lastestObj.returnIssueno;
                    [[SQLiteManager share]insertDataOfArray:nil orDictionary:lastestDict inTable:@"T_DoubleChromosphere"];
                    
                    [[[ThroadToServer shareThroadToServer]initWithParams:^(NSArray *array3){
                        [self insertData:array3 needInsertDataBase:YES haveIndexSet:1];
                        
                    }] loadDoubleChromospheresByIssueno:lastestObj.returnIssueno andRows:diff - 1];

                } else {
                    
                    [self.tableView reloadData];

                }
            }] loadDoubleChromosphereByIssueno:nil];
   
        } else {
            [self insertData:array1 needInsertDataBase:NO haveIndexSet:-1];
 
        }
        

    };
    
    [[SQLiteManager share]queryDataInTable:@"T_DoubleChromosphere" andReturnBlock:returnBlock andOrderBy:order andSort:@"desc" andResultCount:CRow withParameter:param andOperate:operate andValue:issueno, nil];

}

- (void)insertData:(NSArray *)array needInsertDataBase:(BOOL)flag haveIndexSet:(NSInteger)indexOfIndexSet {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (array != nil) {
            if (!flag) {
                [self.array addObjectsFromArray:array];
                
            } else {
                NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(indexOfIndexSet < 0 ? self.array.count : indexOfIndexSet, array.count)] ;
                [self.array insertObjects:array atIndexes:indexSet];
                [[SQLiteManager share]insertDataOfArray:array orDictionary:nil inTable:@"T_DoubleChromosphere"];
                
            }
            
            dispatch_sync(dispatch_get_global_queue(0, 0), ^{
                NSArray *acArray = [[Tools shareTools]type1:array];
                for (NSInteger i = acArray.count; i > 1; i--) {
                    NSArray *allRedArray = ((DoubleChromosphere *)acArray[i - 2]).returnRedBall;
                    NSString *allSomeStr = ((DoubleChromosphere *)acArray[i - 1]).returnSomebody;
                    if ([allRedArray containsObject:allSomeStr]) {
                        [((DoubleChromosphere *)acArray[i - 2]) setNextSomeBody:allSomeStr];
                        
                    }
                    
                }
            });
            
        }
        [self.indicatorView stopAnimating];
        [self.tableView reloadData];
    });
    
}
@end
